class Solution {
public:
    vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {
        int n = prerequisites.size();
        vector<int> inDegree(numCourses);       // 入度表，即每门课需要几门前置课程
        unordered_map<int, vector<int>> hash;   // 这门课学完能学哪些课
        for(int i = 0; i < n; i++)
        {
            inDegree[prerequisites[i][0]]++;
            hash[prerequisites[i][1]].push_back(prerequisites[i][0]);
        }

        queue<int> q;
        for(int i = 0; i < numCourses; i++)
            if(inDegree[i] == 0)    // 该课度为0，则放入队列，相当于可以学习这门课
                q.push(i);
        
        vector<int> ret;
        while(!q.empty())
        {
            int curCourse = q.front();
            q.pop();
            ret.push_back(curCourse);
            for(auto &cp : hash[curCourse])
            {
                if(--inDegree[cp] == 0)
                    q.push(cp);
            }
        }

        if(ret.size() != numCourses)
            return { };
        return ret;
    }
};